﻿package net.wangit.user.role;

import java.util.Map;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.DBFactory;
import net.wangit.user.privilege.PrivilegeUtil;
import net.wangit.util.Checker;


public class RoleFactory {

	private static final String SQL_ROLE = "select * from AROLE where roleid=?";
	private static final String SQL_PRIVILEGES = "select * from AROLEPRIVILEGE where roleid=?";

	public RoleFactory() {
	}

	public static Role getRole(String roleId) throws Exception {
		Role role = RoleCache.get(roleId);
		if (role == null) {
			role = createRole(roleId);
			RoleCache.put(roleId, role);
		}
		return role;
	}

	private static Role createRole(String roleId) throws Exception {
		DB db = DBFactory.getDB();
		MapList list = db
				.query("select * from AROLE where roleid=?", roleId, 2);
		if (Checker.isEmpty(list)) {
			return null;
		} else {
			Row row = list.getRow(0);
			Role role = new Role(roleId);
			role.setName(row.get("rolename"));
			role.setValid("1".equals(row.get("enabled")));
			role.setPrivileges(getPrivileges(db, roleId));
			return role;
		}
	}

	private static Map getPrivileges(DB db, String roleId) throws Exception {
		MapList list = db.query("select * from AROLEPRIVILEGE where roleid=?",
				roleId, 2);
		return PrivilegeUtil.getPrivileges(list);
	}
}
